package com.wechat.config;

import java.util.Set;

import com.swak.router.RouterFunction;
import com.swak.utils.Sets;
import com.wechat.annotation.Cmd;
import com.wechat.command.Commands;
import com.wechat.service.cmds.CmdFunction;
import com.wechat.service.cmds.CmdRoute;

import lombok.Getter;
import lombok.experimental.Accessors;

/**
 * CmdBean.
 * 
 * @author DELL
 */
@Getter
@Accessors(chain = true)
public class CmdBean {

	private static Set<CmdBean> CMDS = Sets.newHashSet();

	private final String name;
	private final Commands command;
	private final String summary;
	private final String[] example;
	private final String method;
	private final Cmd cmd;
	private final Object service;

	CmdBean(Cmd cmd, Object service) {
		this.cmd = cmd;
		this.service = service;
		this.name = cmd.name();
		this.command = cmd.command();
		this.summary = cmd.summary();
		this.example = cmd.example();
		this.method = cmd.method();
	}

	public static CmdBean New(Cmd cmd, Object service) {
		CmdBean bean = new CmdBean(cmd, service);
		CMDS.add(bean);
		return bean;
	}

	public static Set<CmdBean> cmds() {
		return CMDS;
	}

	public static RouterFunction<CmdRoute> newCmdRouter() {
		Set<CmdFunction> handlers = Sets.newHashSet();
		for (CmdBean bean : CmdBean.cmds()) {
			handlers.add(new CmdFunction(bean));
		}
		RouterFunction<CmdRoute> router = handlers.stream().map(handler -> handler.route()).reduce(RouterFunction::and)
				.orElse(null);
		return router;
	}
}
